package com.cyq.dascma.controller;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyq.dascma.constant.ValidaEnum;
import com.cyq.dascma.dto.ScoreInfoDto;
import com.cyq.dascma.entity.Rule;
import com.cyq.dascma.entity.Score;
import com.cyq.dascma.exception.ServiceException;
import com.cyq.dascma.handler.valida.impl.ScoreValidaImpl;
import com.cyq.dascma.result.Result;
import com.cyq.dascma.result.ResultGenerator;
import com.cyq.dascma.service.RuleService;
import com.cyq.dascma.service.ScoreService;
import com.cyq.dascma.util.RequestUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * dingwen
 * 2021/4/4 14:45
 **/
@Api(tags = "成绩模块")
@RestController
@RequestMapping("/score")
public class ScoreController {
    private final ScoreService scoreService;
    private final RuleService ruleService;

    @Autowired
    ScoreController(ScoreService scoreService,
                    RuleService ruleService) {
        this.scoreService = scoreService;
        this.ruleService = ruleService;
    }

    /*
     *分页查询所有学生成绩信息列表  info
     * @param []
     * @return com.cyq.dascma.result.Result
     */
    @ApiOperation(value = "查询所有学生成绩信息列表  info")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "studentId", value = "学号", required = false),
            @ApiImplicitParam(name = "studentName", value = "学生姓名", required = false),
            @ApiImplicitParam(name = "courseId", value = "课程编号", required = false),
            @ApiImplicitParam(name = "clazzName", value = "班级名称", required = false),
            @ApiImplicitParam(name = "pageSize", value = "每页多少条", required = true),
            @ApiImplicitParam(name = "pageNum", value = "第几页", required = true),
    })

    @GetMapping("info/page")
    public Result get(@RequestParam(value = "studentId", required = false) String studentId,
                      @RequestParam(value = "studentName", required = false) String studentName,
                      @RequestParam(value = "courseId", required = false) String courseId,
                      @RequestParam(value = "clazzName", required = false) String className,
                      @RequestParam(value = "clazzId", required = false) String clazzId,
                      @RequestParam(value = "pageSize") Integer pageSize,
                      @RequestParam("pageNum") Integer pageNum, HttpServletRequest request) {
        Map<String, Object> params = RequestUtil.getParameterMap(request);
        params.put("offset", ((pageNum - 1) * pageSize));
        params.put("limit", (pageSize));
        List<ScoreInfoDto> scoreInfoDtoList = scoreService.findScoreInfoList(params);
        return ResultGenerator.genOkResult(scoreInfoDtoList);
    }


    /*
     * 根据studentId修改学生成绩信息
     * @param Score
     * @return Result
     */
    @ApiOperation("根据studentId修改学生成绩信息")
    @ApiImplicitParam(name = "Score", value = "成绩实体", required = true, dataType = "score", paramType = "body")
    @PutMapping("/modify")
    public Result modify(@RequestBody Score score) {
        try {
            new ScoreValidaImpl().valida(ValidaEnum.MODIFY, score);
        } catch (ServiceException serviceException) {
            return serviceException.result();
        }
        boolean flag = scoreService.updateById(score);
        return flag ? ResultGenerator.genOkResult("更新学生成绩信息成功") : ResultGenerator.genFailureResult("更新学生成绩信息失败");
    }

    @ApiOperation("根据学生ID & 课程ID添加成绩")
    @ApiImplicitParam(name = "score", value = "成绩实体", required = true, dataType = "score", paramType = "body")
    @PostMapping("/add")
    public Result add(@RequestBody Score score) {
        try {
            new ScoreValidaImpl().valida(ValidaEnum.ADD, score);
        } catch (ServiceException serviceException) {
            return serviceException.result();
        }
        score.setScoreId(IdUtil.randomUUID());
        boolean flag = scoreService.save(score);

        return flag ? ResultGenerator.genOkResult("添加学生成绩信息成功") : ResultGenerator.genFailureResult("添加学生成绩信息失败");
    }

    /*
     *获取所有成绩信息，按照计算规则计算，并录入数据库
     * @param []
     * @return com.cyq.dascma.result.Result
     */
    @ApiOperation("成绩计算 & 录入数据库")
    @GetMapping("/calculate")
    public Result get() {
        List<Score> scoreList = scoreService.list();
        scoreList.stream().parallel().forEach(score -> {
            Rule rule = ruleService.getOne(new QueryWrapper<Rule>()
                                        .and(wrapperCourseId -> wrapperCourseId.eq("course_id",score.getCourseId()))
                                        .and(wrapperTeacherId -> wrapperTeacherId.eq("teacher_id",score.getTeacherId())));
            Double finalScore = score.getScoreAttendance() * rule.getRuleAttendance()
                    + score.getScoreClazz() * rule.getRuleClazz()
                    + score.getScoreHomework() * rule.getRuleHomework()
                    + score.getScoreMiddle() * rule.getRuleMiddle()
                    + score.getScoreEnd() * rule.getRuleEnd();
            score.setScoreFinal(new BigDecimal(finalScore).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue());
        });
        boolean flag = scoreService.updateBatchById(scoreList);
        return flag ? ResultGenerator.genOkResult(scoreList).setMessage("成绩计算成功") : ResultGenerator.genFailureResult("成绩计算失败");
    }

    /*
     *查询成绩总记录条数
     * @param []
     * @return com.cyq.dascma.result.Result
     */
    @ApiOperation("查询成绩总记录条数")
    @GetMapping("/total")
    public Result getTotal() {
        return ResultGenerator.genOkResult(scoreService.count());
    }
}
